import { Table as AntdTable, Button, Input, TreeDataNode } from "antd";
import React, { FC, useContext, useEffect, useMemo, useRef, useState } from "react";
import { CommonComponentProps } from "@/pages/lowCodeEditorPlus/interface";
import { useMaterialDrop } from "@/pages/lowCodeEditorPlus/hooks/useMaterialDrop";
import { useDrag } from "react-dnd";
import TableOperationColumn from "../TableOperationColumn/dev";
import { SyncOutlined } from "@ant-design/icons";
import { ContainerEmpty } from "@/pages/lowCodeEditorPlus/materialItems/common-components/ContainerEmpty";
import { accept } from "./setter";
import { SizeType } from "@/types/antd-types";
import { LowCodePageContext } from '@/pages/lowCodeEditorPlus/contextProvider/LowCodePageProvider';
import { cloneDeep } from "lodash-es";
const Table: FC<CommonComponentProps> = ({
  id,
  name,
  desc,
  alias,
  children,
  styles,
  pagination,
  containerUnitType,
  size = "middle",
  buttonGroup,
  showHeaderTool,
  showSearch,
  showFresh,
  primaryKey
}) => {
  const { canDrop, drop } = useMaterialDrop(accept.body, id);
  const { drop: buttonDrop } = useMaterialDrop(accept.buttonGroup, id, "buttonGroup");
  const [_, drag] = useDrag({
    type: name,
    item: {
      type: name,
      dragType: "move",
      id: id,
      containerUnitType,
    },
  });
  const columnTitleClass = useMemo(() => {
    const obj = {
      large: "-m-4 p-4",
      middle: "-my-3 -mx-2 p-3",
      small: "-m-2 p-2",
    };
    return obj[size as SizeType || 'middle'];
  }, [size]);

  const columns = useMemo(() => {
    return React.Children.map(children, (item: any) => {
      const { name, title, dataIndex, id: cid, width, buttonGroup } = item.props || {};
      if (name === "TableColumn") {
        return {
          title: (
            <div className={`${columnTitleClass}`} data-component-id={cid}>
              {title}
            </div>
          ),
          dataIndex: dataIndex,
          width: width || "auto",
          render: (_: unknown, record: any) => (
            <div className={`${columnTitleClass}`} data-component-id={cid}>
            <span>假数据</span>
            </div>
          ),
        };
      } else {
        return {
          title: (
            <div className={`${columnTitleClass}`} data-component-id={cid} data-component-bind-unit="buttonGroup">
              {title}
            </div>
          ),
          width: width || "auto",
          align: "center",
          render: (_: unknown, record: any, index: number) => (
            <TableOperationColumn id={cid} index={index} size={size}>
              {buttonGroup}
            </TableOperationColumn>
          ),
        };
      }
    });
  }, [children]);

  useEffect(()=>{
    getComponentProperties(children)
  },[children])
  
  const { setContextProperties } = useContext(LowCodePageContext);
  function getComponentProperties(children: React.ReactNode){
    const arr = [] as TreeDataNode[]
    const operationColumnIds: string[] = []
    React.Children.map(children, (item: any)=>{
      const { title, dataIndex, id: oid} = item?.props || {};
      if(item.props.name === "TableColumn"){
        arr.push({
          title,
          key: dataIndex
        })
      }else{
        operationColumnIds.push(oid)
      }
    })
    if(primaryKey){
      arr.unshift({
        title: "主键",
        key: primaryKey
      })
    }
    // const members={
    //   title: "成员",
    //   key: "table_columns",
    //   disabled: true,
    //   children:arr
    // }
    const tableObj={
      title: `${alias}[${desc}]`,
      key: name,
      disabled: true,
      children:[
        {title: '全部数据', key: 'items', type: 'array'},
        {title: '选中数据', key: 'selectedItems', type: 'array'},
        {title: '未选中数据', key: 'unSelectedItems', type: 'array'},
        {title: '当前页码', key: 'currentPage', type: 'number'},
        {title: '总数据条数', key: 'total', type: 'number'},
      ]
    }
    setContextProperties(id, tableObj)

    const recordChildren = cloneDeep(arr).map(ele=>{
      ele.key = `record.${ele.key}`
      return ele
    })
    const rowObj={
      title: "当前行记录",
      key: "Row",
      disabled: true,
      parentId: id,
      children:[
        {title: '行数据', key: 'record', children: recordChildren, type: 'object'},
        {title: '索引', key: 'index', type: 'number'},
      ]
    }
    operationColumnIds.forEach(oid=>setContextProperties(oid, rowObj))
  }

  const dataSource = useMemo(() => {
    const keys: string[] = React.Children.map(children, (item: any) => item.props?.dataIndex);
    return Array.from({ length: 6 }).map((_, i) => {
      // const obj = keys.reduce((acc, cur) => {
      //   acc[cur] = "假数据";
      //   return acc;
      // }, {} as Record<string, any>);
      return {
        key: i,
        // ...obj,
      };
    });
  }, [children]);

  const paginationConf = pagination
    ? {
        pageSize: pagination.pageSize,
        total: 100,
        showTotal: (total: number) => (pagination.showTotal ? `共 ${total} 条` : null),
        showQuickJumper: pagination.showQuickJumper,
        onChange: (page: number, size: number) => {},
      }
    : false;
  return (
    <section className="flex flex-col h-full gap-y-3" data-component-id={id}>
      {showHeaderTool && (
        <header className="flex gap-2">
          {showSearch && <Input.Search style={{ width: "200px" }} allowClear onSearch={() => {}} />}
          <div className="flex flex-1 w-1 gap-1" ref={buttonDrop} data-component-id={id} data-component-unit-type="buttonGroup">
            {buttonGroup}
            {buttonGroup?.length === 0 && <ContainerEmpty desc="按钮配置" />}
          </div>
          {showFresh && <Button shape="circle" icon={<SyncOutlined />} />}
        </header>
      )}
      <div
        className="flex-1 min-h-20"
        style={styles}
        ref={node => drop(drag(node))}
        data-component-id={id}
        data-component-unit-type="body"
      >
        <AntdTable
          id={`table_dev_${id}`}
          size={size}
          columns={columns}
          dataSource={dataSource}
          pagination={paginationConf}
          bordered
          //  className="fullHeight"
        />
      </div>
    </section>
  );
};

export default Table;
